﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Wangzeran.CodeMaker.Core.Util
{
    /// <summary>
    /// 字符串工具
    /// </summary>
    public class StringUtil
    {
        /// <summary>
        /// 匹配key=value
        /// </summary>
        private const string PATTERN_KEY_VALUE = "\\S*?=\"\\S+?\"";
        /// <summary>
        /// 匹配标签
        /// </summary>
        private const string PATTERN_TAG = "<c:.+?\".?/>";

        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string[] SplitString(string str)
        {
            string[] lines = 
                str.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

            return lines;
        }

        /// <summary>
        /// 清空StringBuilder
        /// </summary>
        /// <param name="sb">StringBuilder对象</param>
        public static void ClearStringBuilder(StringBuilder sb)
        {
            sb.Remove(0, sb.Length);
        }

        /// <summary>
        /// 解析Key=Value字符串
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static IDictionary<string, string> ParseKeyValues(string str)
        {
            IDictionary<string, string> dic = new Dictionary<string, string>();
            if (str == null)
            {
                return dic;
            }
            MatchCollection matchs = Regex.Matches(str, PATTERN_KEY_VALUE, RegexOptions.IgnoreCase);
            foreach (Match match in matchs)
            {
                if (match.Success)
                {
                    string[] arr = ParseKeyValue(match.Value);
                    dic.Add(arr[0].ToLower().Trim(), arr[1].Replace("\"", String.Empty).Trim());
                }
            }

            return dic;
        }

        /// <summary>
        /// 解析Key=Value字符串
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static string[] ParseKeyValue(string str)
        {
            string[] arr = str.Replace(";", String.Empty).Split('=');
            if (arr.Length < 2)
            {
                return null;
            }
            return arr;
        }

        /// <summary>
        /// 是否为标签
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static bool IsTag(string str)
        {
            try
            {
                return Regex.IsMatch(str, PATTERN_TAG);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
